package com.jy.wms.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.BaseService;
import com.jy.wms.common.base.ServiceException;
import com.jy.wms.common.base.SetAndModifyModel;
import com.jy.wms.common.base.SucessException;
import com.jy.wms.dao.WmsLoadingMapper;
import com.jy.wms.pojo.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: WmsLoadingService.java
 * @Description: 装车单
 * @Author Yjs
 * @Date Wed Jan 31 16:01:23 GMT+08:00 2018
 */

@Service
public class WmsLoadingService extends BaseService<WmsLoadingMapper, WmsLoading> {
    /**
     * 分页查询
     *
     * @param entity 实体
     * @return Page<WmsShipmentOrder>
     */
    @BaseServiceDescribe(moduleName = "出库发运信息", btnName = "分页查询出库发运信息")
    public Page<WmsShipmentOrder> baseSelectPage(WmsShipmentOrder entity) {
        PageHelper.startPage(entity.getPage(), entity.getRows());
        //发运状态3：部分发运 4：全部发运
        List<String> fyztList = new ArrayList<>();
        fyztList.add("3");
        fyztList.add("4");
        //拣货状态1：部分拣货 2：全部拣货
        List<String> jhztList = new ArrayList<>();
        jhztList.add("1");
        jhztList.add("2");
        return (Page<WmsShipmentOrder>) dao.baseSelectPage(entity, fyztList, jhztList);
    }

    /**
     * 发运单创建装车单
     *
     * @param stringBuilder
     * @param stringBuilder2
     * @param stringBuilder3
     * @throws RuntimeException
     */
    public void returnType(StringBuilder stringBuilder, StringBuilder stringBuilder2, StringBuilder stringBuilder3) throws RuntimeException {
        if (stringBuilder.length() > 0) {
            throw new RuntimeException(stringBuilder.toString() + "发运编号已加入装车单,不可重复创建");
        }
        if (stringBuilder2.length() > 0) {
            throw new RuntimeException(stringBuilder2.toString() + "发运编号未装箱,不可创建装车单");
        }
        if (stringBuilder3.length() > 0) {
            throw new RuntimeException(stringBuilder3.toString() + "发运编号已发运,不可创建装车单");
        }
    }

    /**
     * 协助发货创建装车单
     *
     * @param stringBuilder
     * @param stringBuilder2
     * @throws RuntimeException
     */
    public void returnType2(StringBuilder stringBuilder, StringBuilder stringBuilder2) throws RuntimeException {
        if (stringBuilder.length() > 0) {
            throw new RuntimeException(stringBuilder.toString() + "订单号已加入装车单,不可重复创建");
        }
        if (stringBuilder2.length() > 0) {
            throw new RuntimeException(stringBuilder2.toString() + "订单号已发运,不可创建装车单");
        }
    }
    /**
     * 新增装车单信息
     * @param wmsLoading
     * @param hzid
     * @param cjr
     * @param ckid
     * @throws Exception
     */
    @BaseServiceDescribe(moduleName = "出库发运信息", btnName = "创建装车单")
    @Transactional
    public void addLoading(WmsLoading wmsLoading, String hzid, String cjr, String ckid) throws Exception {
        WmsOwner wmsOwner = dao.searchHz(hzid, ckid);
        //装车单  0否 1是
        if ("0".equals(wmsOwner.getZcd())) {
            throw new ServiceException("该货主未设置创建装车单");
        } else {
            //装车单
            StringBuilder stringBuilder = new StringBuilder();
            //装箱
            StringBuilder stringBuilder2 = new StringBuilder();
            //发运状态(0、初始 1、部分分配2、全部分配;可创建装车单)
            StringBuilder stringBuilder3 = new StringBuilder();
            for (WmsLoadingDetailed wmsLoadingDetailed : wmsLoading.getWmsLoadingDetailedList()) {
                //查询发运订单信息
                WmsShipmentOrder wmsShipmentOrder = dao.searchFydd(wmsLoadingDetailed.getFyid());
                //判断是否装箱(装箱状态（0、未装箱 1、部分装箱 2、全部装箱）)
                if ("0".equals(wmsShipmentOrder.getZxzt())) {
                    stringBuilder2.append(wmsShipmentOrder.getFybh());
                    stringBuilder2.append(",");
                }
                if (!"".equals(wmsShipmentOrder.getZcdbh()) && wmsShipmentOrder.getZcdbh() != null && !"0".equals(wmsShipmentOrder.getZcdbh())) {
                    stringBuilder.append(wmsShipmentOrder.getFybh());
                    stringBuilder.append(",");
                }
                if (!"0".equals(wmsShipmentOrder.getFyzt()) && !"1".equals(wmsShipmentOrder.getFyzt()) && !"2".equals(wmsShipmentOrder.getFyzt())) {
                    stringBuilder3.append(wmsShipmentOrder.getFybh());
                    stringBuilder3.append(",");
                }
            }
            returnType(stringBuilder, stringBuilder2, stringBuilder3);
            wmsLoading.setId(UUIDUtils.uuid());
            //生成装车单编号
            String zcdbh = searchZcdbh();
            wmsLoading.setZcdbh(zcdbh);
            wmsLoading.setCkid(ckid);
            wmsLoading.setHzid(hzid);
            wmsLoading.setCjr(cjr);
            Integer i = dao.addLoading(wmsLoading);
            if (i > 0) {
                i = dao.updateZcdbh(wmsLoading.getWmsLoadingDetailedList(), zcdbh);
                if (i > 0) {
                    throw new SucessException("创建装车单信息成功");
                } else {
                    throw new RuntimeException("更改装车单号失败");
                }
            } else {
                throw new RuntimeException("创建装车单信息失败");
            }
        }
    }

    /**
     * 协助发货创建装车单信息
     *
     * @param wmsLoading
     * @param hzid
     * @param cjr
     * @param ckid
     * @throws Exception
     */
    @BaseServiceDescribe(moduleName = "协助发货创建装车单信息", btnName = "协助发货创建装车单信息")
    @Transactional
    public void assistAddLoading(WmsLoading wmsLoading, String hzid, String cjr, String ckid) throws Exception {
        WmsOwner wmsOwner = dao.searchHz(hzid, ckid);
        //装车单  0否 1是
        if ("0".equals(wmsOwner.getZcd())) {
            throw new ServiceException("该货主未设置创建装车单");
        } else {
            //装车单
            StringBuilder stringBuilder = new StringBuilder();
            //下发状态(初始才可以创建)
            StringBuilder stringBuilder2 = new StringBuilder();
            for (WmsLoadingDetailed wmsLoadingDetailed : wmsLoading.getWmsLoadingDetailedList()) {
                //查询协助订单信息
                WmsAssistDelivery wmsAssistDelivery = dao.searchAssist(wmsLoadingDetailed.getFyid());
                if (!"".equals(wmsAssistDelivery.getZcdbh()) && wmsAssistDelivery.getZcdbh() != null && !"0".equals(wmsAssistDelivery.getZcdbh())) {
                    stringBuilder.append(wmsAssistDelivery.getDdh());
                    stringBuilder.append(",");
                }
                if (!"0".equals(wmsAssistDelivery.getXfzt())) {
                    stringBuilder2.append(wmsAssistDelivery.getDdh());
                    stringBuilder2.append(",");
                }
            }
            returnType2(stringBuilder, stringBuilder2);
                wmsLoading.setId(UUIDUtils.uuid());
                //生成装车单编号
                String zcdbh = searchZcdbh();
                wmsLoading.setZcdbh(zcdbh);
                wmsLoading.setCkid(ckid);
                wmsLoading.setHzid(hzid);
                wmsLoading.setCjr(cjr);
                Integer i = dao.addLoading(wmsLoading);
                if (i > 0) {
                    i = dao.assistUpdateZcdbh(wmsLoading.getWmsLoadingDetailedList(), zcdbh);
                    if (i > 0) {
                        throw new SucessException("创建装车单信息成功");
                    } else {
                        throw new RuntimeException("更改装车单号失败");
                    }
                } else {
                    throw new RuntimeException("创建装车单信息失败");
                }
        }
    }
    /**
     * 生成装车单编号
     *
     * @return
     */
    public String searchZcdbh() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date time = new Timestamp(System.currentTimeMillis());
        String zcdbhTime = sdf.format(time);
        //模糊查询装车单编号
        String zcdbh = dao.searchZcdbh(zcdbhTime);
        //如果数据库内有装车单编号
        if (!"".equals(zcdbh) && zcdbh != null) {
            String[] maxNum = zcdbh.split(zcdbhTime);
            //取到日期后面的最大值
            long maxZcdbh = Long.parseLong(maxNum[1]);
            //最大值加1
            maxZcdbh += 1;
            zcdbh = zcdbhTime + maxZcdbh;
        } else {
            zcdbh = zcdbhTime + "1";
        }
        return zcdbh;
    }

    /**
     * 承运人模糊查询
     *
     * @param cyrmc
     * @return
     */
    public List<WmsLoading> searchCyr(String cyrmc, String hzid, String ckid) {
        return dao.searchCyr(cyrmc, hzid, ckid);
    }

    /**
     * 承运车辆模糊查询
     * @param cph
     * @param cyrid
     * @param hzid
     * @param ckid
     * @return
     */
    public List<WmsLoading> searchCph(String cph, String cyrid, String hzid, String ckid) {
        return dao.searchCph(cph, cyrid, hzid, ckid);
    }
    /**
     * 抵扣审核
     *
     * @param setAndModifyModel
     * @param hzid
     * @param ckid
     */
    @BaseServiceDescribe(moduleName = "抵扣审核", btnName = "抵扣审核")
    @Transactional
    public void deductible(SetAndModifyModel setAndModifyModel, String hzid, String ckid) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        for (String id : setAndModifyModel.getIds()) {
            Boolean flag = true;
            //借货001;抵扣002;
            String fylx = "抵扣";
            String lxdm = "002";
            //查询发运订单数据
            WmsShipmentOrder wmsShipmentOrder = dao.searchDd(id);
            if (lxdm.equals(wmsShipmentOrder.getLxdm())) {
                //查询发运明细订单数据
                List<WmsShipmentOrderDetailed> wmsShipmentOrderDetailedList = dao.searchDdMx(id);
                for (WmsShipmentOrderDetailed wmsShipmentOrderDetailed : wmsShipmentOrderDetailedList) {
                    //借货单预期数量等于抵扣数量,借货抵扣状态为"全部抵扣"；
                    //借货单预期数量大于抵扣数量,借货抵扣状态为"部分抵扣"；
                    String jhdkzt = null;
                    Integer yqsl = Integer.parseInt(wmsShipmentOrderDetailed.getYqsl());
                    Integer dksl = Integer.parseInt(wmsShipmentOrderDetailed.getDksl());
                    if (wmsShipmentOrderDetailed.getYqsl().equals(wmsShipmentOrderDetailed.getDksl())) {
                        jhdkzt = "2";
                    } else if (yqsl > dksl) {
                        jhdkzt = "1";
                        flag = false;
                    }
                    //修改发运订单明细借货抵扣状态状态
                    int i = dao.updateJhdkzt(wmsShipmentOrderDetailed.getId(), jhdkzt);
                    if (i <= 0) {
                        throw new ServiceException("修改发运订单明细借货抵扣状态状态失败");
                    }
                }
            } else {
                stringBuilder.append(wmsShipmentOrder.getBcbh());
                stringBuilder.append(",");
            }
            String jhdkzt2 = null;
            if (flag) {
                jhdkzt2 = "2";
            } else {
                jhdkzt2 = "1";
            }
            //修改发运订单借货抵扣状态状态
            int j = dao.updateJhdkzt2(wmsShipmentOrder.getId(), jhdkzt2);
            if (j <= 0) {
                throw new ServiceException("修改发运订单借货抵扣状态状态失败");
            }
        }
        if (stringBuilder.length() != 0) {
            throw new ServiceException(stringBuilder.toString() + "订单,单据类型不符,请选择单据类型为抵扣的发运订单");
        } else {
            throw new SucessException("抵扣审核成功");
        }
    }

    /**
     * 打印装车单查询
     * @param list
     * @param hzid
     * @param ckid
     * @return
     */
    @BaseServiceDescribe(moduleName = "打印装车单", btnName = "打印装车单")
    public List<WmsLoading> printLoading(List<String> list, String hzid, String ckid) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        List<WmsLoading> wmsLoadingList = new ArrayList<>();
        List<String> stringList = new ArrayList<>();
        WmsLoading wmsLoading = null;
        //循环发运id
        for (String id : list) {
            WmsShipmentOrder wmsShipmentOrder = dao.searchFydd(id);
            if (!"".equals(wmsShipmentOrder.getZcdbh()) && wmsShipmentOrder.getZcdbh() != null && !"0".equals(wmsShipmentOrder.getZcdbh())) {
                stringList.add(wmsShipmentOrder.getZcdbh());
            } else {
                stringBuilder.append(wmsShipmentOrder.getFybh());
                stringBuilder.append(",");
            }
        }
        if (stringBuilder.length() > 0) {
            throw new ServiceException(stringBuilder.toString() + "订单未创建装车单,不可打印");
        } else {
            //去除重复装车单编号
            stringList = remove(stringList);
            for (String zcdbh : stringList) {
                wmsLoading = new WmsLoading();
                //统计箱编号数
                List<WmsLoading> wmsLoadingList1 = dao.countSl(zcdbh, list);
                //承运商
                wmsLoading.setCyrmc(wmsLoadingList1.get(0).getCyrmc());
                //承运车辆
                wmsLoading.setCycl(wmsLoadingList1.get(0).getCycl());
                //装箱数
                wmsLoading.setZxs(String.valueOf(wmsLoadingList1.size()));
                //统计总单数
                List<WmsLoading> wmsLoadingList2 = dao.countSl2(zcdbh, list);
                wmsLoading.setZds(wmsLoadingList2.get(0).getZds());
                //装车单编号
                wmsLoading.setZcdbh(zcdbh);
                //查询装车单明细
                List<WmsLoadingDetailed> wmsLoadingDetailedList = dao.searchMx(zcdbh, list);
                wmsLoading.setWmsLoadingDetailedList(wmsLoadingDetailedList);
                wmsLoadingList.add(wmsLoading);
            }
        }
        return wmsLoadingList;
    }

    /**
     * 协助发货打印装车单查询
     *
     * @param list
     * @param hzid
     * @param ckid
     * @return
     */
    @BaseServiceDescribe(moduleName = "协助发货打印装车单", btnName = "协助发货打印装车单")
    public List<WmsLoading> assistPrintLoading(List<String> list, String hzid, String ckid) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        List<WmsLoading> wmsLoadingList = new ArrayList<>();
        List<String> stringList = new ArrayList<>();
        WmsLoading wmsLoading = null;
        //循环发运id
        for (String id : list) {
            //查询协助订单信息
            WmsAssistDelivery wmsAssistDelivery = dao.searchAssist(id);
            if (!"".equals(wmsAssistDelivery.getZcdbh()) && wmsAssistDelivery.getZcdbh() != null && !"0".equals(wmsAssistDelivery.getZcdbh())) {
                stringList.add(wmsAssistDelivery.getZcdbh());
            } else {
                stringBuilder.append(wmsAssistDelivery.getDdh());
                stringBuilder.append(",");
            }
        }
        if (stringBuilder.length() > 0) {
            throw new ServiceException(stringBuilder.toString() + "订单号未创建装车单,不可打印");
        } else {
            //去除重复装车单编号
            stringList = remove(stringList);
            for (String zcdbh : stringList) {
                wmsLoading = new WmsLoading();
                //统计箱编号数
                List<WmsLoading> wmsLoadingList1 = dao.assistCountSl(zcdbh, list);
                //承运商
                wmsLoading.setCyrmc(wmsLoadingList1.get(0).getCyrmc());
                //承运车辆
                wmsLoading.setCycl(wmsLoadingList1.get(0).getCycl());
                //总单数
                wmsLoading.setZxs(String.valueOf(wmsLoadingList1.size()));
                //统计总单数
                List<WmsLoading> wmsLoadingList2 = dao.assistCountSl2(zcdbh, list);
                wmsLoading.setZds(wmsLoadingList2.get(0).getZds());
                //装车单编号
                wmsLoading.setZcdbh(zcdbh);
                //查询装车单明细
                List<WmsLoadingDetailed> wmsLoadingDetailedList = dao.assistSearchMx(zcdbh, list);
                wmsLoading.setWmsLoadingDetailedList(wmsLoadingDetailedList);
                wmsLoadingList.add(wmsLoading);
            }
        }
        return wmsLoadingList;
    }
    /**
     * 装车单编号去重
     *
     * @param stringList
     * @return
     */
    public List<String> remove(List<String> stringList) {
        for (int i = 0; i < stringList.size() - 1; i++) {
            for (int j = i + 1; j < stringList.size(); j++) {
                if (stringList.get(i).equals(stringList.get(j))) {
                    stringList.remove(j);
                    j--;
                }
            }
        }
        return stringList;
    }
}
